import { useGoto } from '@/hooks';
import { useUserContext } from '@/hooks/userHooks';
import { ROUTE_KEY } from '@/routers/menus';
import { useOrganizations } from '@/services/org';
import { currentOrg } from '@/utils';
import { LOCAL_CURRENT_ORG } from '@/utils/constance';
import { Select, Space } from 'antd';
import _ from 'lodash';
import { useEffect } from 'react';

/**
* 门店选择器
*/
interface OrgItem {
  name:string,
  id:string
}
const OrgSelect = () => {
  const { data, refetch } = useOrganizations(1, 10, true);
  const { go } = useGoto();
  const { setStore } = useUserContext();
  useEffect(() => {
    if (currentOrg()?.value) {
      setStore({
        currentOrg: currentOrg().value,
      });
    } else {
      go(ROUTE_KEY.No_Org);
    }
  }, []);
  const onSearch = _.debounce((name:string) => {
    refetch({
      name,
    });
  }, 500);
  const onChangeHandler = (val:{ value:string, label:string }) => {
    setStore({
      currentOrg: val.value,
    });
    localStorage.setItem(LOCAL_CURRENT_ORG, JSON.stringify(val));
  };
  return (
    <div>
      <Space>
        选择门店：
        <Select
          showSearch
          placeholder="请选择门店"
          style={{ width: 200 }}
          onSearch={onSearch}
          filterOption={false}
          defaultValue={currentOrg()}
          onChange={onChangeHandler}
          labelInValue
          clearIcon
        >
          {
            data?.map((item:OrgItem) => (
              <Select.Option
                key={item.id}
                value={item.id}
              >
                { item.name }
              </Select.Option>
            ))
        }
        </Select>
      </Space>
    </div>
  );
};

export default OrgSelect;
